from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api.urlfetch import fetch
import os
import datetime
import tables

from html import DropDown, Link


class Login(webapp.RequestHandler):
    'facilitates mock login'
    def __init__(self):
        webapp.RequestHandler.__init__(self) #calling parent constructor
        self.currentSemester = tables.AppState.get_by_key_name('currentState').semester
        self.tas = dict()
        for row in db.GqlQuery("SELECT * FROM Ta WHERE semester = :currentSemester", currentSemester = self.currentSemester):
            assert row.eid not in self.tas.keys()
            self.tas[row.eid] = row

        self.instructors = dict()
        for row in db.GqlQuery("SELECT * FROM Instructor"):
            assert row.eid not in self.instructors.keys()
            self.instructors[row.eid] = row


    def get(self):
        self.renderTemplate()
        
    def post(self):
        eid = self.request.get('eid', default_value="default").lower()
        if eid in self.tas:
            self.response.out.write('''
                <body onload="submitForm()">
                <form name="myForm" method="post" action="/ta">
                <input type="hidden" name="eid" value="'''+eid+'''"/>
                </form>
                <script type='text/javascript'>document.myForm.submit();</script>''')

        elif eid in self.instructors:
            self.response.out.write('''
                <body onload="submitForm()">
                <form name="myForm" method="post" action="/instructor">
                <input type="hidden" name="eid" value="'''+eid+'''"/>
                </form>
                <script type='text/javascript'>document.myForm.submit();</script>''')
        else:
            self.response.out.write("Given eid not valid.")
        self.renderTemplate()

    def renderTemplate(self):
        'Renders the template file login.html'
        sortedTas = [ta for ta in self.tas.values()]
        sortedTas.sort(key = lambda ta : ta.lastName.lower())
        
        sortedInstructors = [instructor for instructor in self.instructors.values()]
        sortedInstructors.sort(key = lambda instructor : instructor.lastName.lower())
        
        templateValues = {
            'login': DropDown(options= ('TA','Instructor','Admin'), name = "login", submitOnChange = True),
            'tas': sortedTas,
            'instructors': sortedInstructors,
            'currentSemester': self.currentSemester,
        }
        path = os.path.join(os.path.dirname(__file__), 'login.html')
        self.response.out.write(template.render(path, templateValues))
        
application = webapp.WSGIApplication([('/login', Login)], debug=True)

def lastName(x):
    return x.lastName

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
